//
//  AddDefectViewController.m
//  Audit
//
//  Created by cc on 15-2-12.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "AddDefectViewController.h"
#import "ConditionViewController.h"
#import "PIDrawerViewController.h"
#import "Defect.h"
#import "DefectConditionViewController.h"
#import "InfiniteScrollPicker.h"
#import "MainPartData.h"
#import "DetailPartData.h"

@interface AddDefectViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    IBOutlet UIButton *componentTitleOne;//部件名称1
    IBOutlet UIButton *componentTitleTwo;//部件名称2
    IBOutlet UIButton *defectInfo;//缺陷
    IBOutlet UIButton *position;//位置
    IBOutlet UIButton *weight;//权重
    IBOutlet UIButton *area;//区域
    IBOutlet UIButton *redepartment;//责任部门
    
    IBOutlet UIButton *defectInfoClean;//缺陷
    IBOutlet UIButton *positionClean;//位置
    IBOutlet UIButton *weightClean;//权重
    IBOutlet UIButton *areaClean;//区域
    IBOutlet UIButton *redepartmentClean;//责任部门
    
    IBOutlet UISwitch *repair;//返修
    IBOutlet UISwitch *perception;//感知
    IBOutlet UIButton *choosePictureButton;//选择照片
    
    IBOutlet UIView *container;
    
    InfiniteScrollPicker *picker;
}
@property (nonatomic , strong) IBOutlet UITableView *detailTableView;
@property (nonatomic , strong) IBOutlet UISearchBar *searchBar;
@end

@implementation AddDefectViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setNavTitle:@"添加缺陷"];
    [self setNavBackButton:nil];
    [self setNavRightButton:@"关闭"];
    
    [self getMainPartInfo];
    
    self.searchBar.delegate=self;
    UITextField *searchField;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]<7.0)
        searchField=[self.searchBar.subviews objectAtIndex:1];
    else
        searchField=[((UIView *)[self.searchBar.subviews objectAtIndex:0]).subviews lastObject];
    searchField.font = [UIFont systemFontOfSize:18.0];
    
    
    self.searchFlag = NO;
    
//    //测试数据
//    self.imgArr = [[NSMutableArray alloc] init];
//    for (int i = 0; i < 15; i++) {
//        [self.imgArr addObject:[UIImage imageNamed:[NSString stringWithFormat:@"s2_%d.png", i]]];
//    }
    picker  = [[InfiniteScrollPicker alloc] initWithFrame:container.bounds];
    [picker setItemSize:CGSizeMake(500, 500)];
//    [picker setImageAry:self.imgArr];
    [container addSubview:picker];
    
//    componentTitleOne.tag=1001;
//    componentTitleTwo.tag=1002;
    defectInfo.tag=1003;
    position.tag=1004;
    weight.tag=1005;
    area.tag=1006;
    redepartment.tag=1007;
    choosePictureButton.tag=1008;
    
    defectInfoClean.tag=1013;
    positionClean.tag=1014;
    weightClean.tag=1015;
    areaClean.tag=1016;
    redepartmentClean.tag=1017;
    
    
    [perception setOn:NO animated:NO];
    [repair setOn:NO animated:NO];
    
    if (!self.currentDefect) {
        self.currentDefect=[[Defect alloc] init];
    }
    else
    {
//        [componentTitleOne setTitle:self.currentDefect.partDesc forState:UIControlStateNormal];
//        [componentTitleTwo setTitle:self.currentDefect.part2Desc forState:UIControlStateNormal];
        [defectInfo setTitle:self.currentDefect.defectDesc forState:UIControlStateNormal];
        [position setTitle:self.currentDefect.locationDesc forState:UIControlStateNormal];
        [weight setTitle:self.currentDefect.weightDesc forState:UIControlStateNormal];
        [area setTitle:self.currentDefect.zoneDesc forState:UIControlStateNormal];
        [redepartment setTitle:self.currentDefect.respareaDesc forState:UIControlStateNormal];
        
        BOOL repairFlag = [self.currentDefect.repairFlag isEqualToString:@"1"]?YES:NO;
        
        BOOL senseFlag = [self.currentDefect.senseFlag isEqualToString:@"1"]?YES:NO;
        
        [repair setOn:repairFlag];
        
        [perception setOn:senseFlag];
        
//        self.searchBar.text = self.currentDefect.part2Desc;
        
        if (self.currentDefect.uploadedFile) {
            [choosePictureButton setTitle:@"" forState:UIControlStateNormal];
            [choosePictureButton setBackgroundImage:self.currentDefect.uploadedFile forState:UIControlStateNormal];
        }
    }
}

-(void)getMainPartInfo
{
    [gAlert showLoading:nil delegate:nil];
    
    [CommunicateWithService communicateWithServiceApiName:@"mainPart.do" finishSelector:@selector(getMainPartInfoFinished:) failSelector:@selector(getMainPartInfoFailed:) delegateObj:self];
}

-(void)getMainPartInfoFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSArray *strDicData=(NSArray *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        self.mainPartInfoArr = [NSMutableArray array];
        
        if ([flag isEqualToString:@"1001"]) {
            for (int i = 0; i < strDicData.count; i++) {
                NSDictionary *defectInfoDic = (NSDictionary *)[strDicData objectAtIndex:i];
                
                MainPartData *dataobj = [[MainPartData alloc] initWithInfo:defectInfoDic];
                
                dataobj.mainPartImg = [UIImage imageNamed:[NSString stringWithFormat:@"s1_%d.png", dataobj.mainPartCode.intValue]];
                
//                dataobj.mainPartImg = [UIImage imageNamed:@"bg.jpg"];

                
//                NSLog(@"%d,%@",dataobj.mainPartCode.intValue,dataobj.mainPartImg);
                
                [self.mainPartInfoArr addObject:dataobj];
            }
            
            NSMutableArray *sortArr = [NSMutableArray array];
            
            //根据code排序 控件默认选中第二个图片 把最后一张图片调到第一张
            for (int x = 11; x <= 25; x++) {
                for (int y = 0; y < self.mainPartInfoArr.count; y++) {
                    if (x!=25) {
                        if (((MainPartData *)[self.mainPartInfoArr objectAtIndex:y]).mainPartCode.intValue == x) {
                            [sortArr addObject:[self.mainPartInfoArr objectAtIndex:y]];
                            break;
                        }
                    }
                    else
                    {
                        if (((MainPartData *)[self.mainPartInfoArr objectAtIndex:y]).mainPartCode.intValue == x) {
                            [sortArr insertObject:[self.mainPartInfoArr objectAtIndex:y] atIndex:0];
                            break;
                        }
                    }
                }
            }
            
            self.mainPartInfoArr = sortArr;
            
            int j = 0;
            
            for (int i = 0; i < strDicData.count; i++) {
                if ([((MainPartData *)[self.mainPartInfoArr objectAtIndex:i]).mainPartKey isEqualToString: self.currentDefect.part]) {
                    if (i!=0) {
                        j = i - 1;
                    }
                    else
                    {
                        j = (int)strDicData.count - 1;
                    }
                    break;
                }
            }
            
            if (j > 0) {
                sortArr = [NSMutableArray array];
                
                int k = j;
                
                for (; j < self.mainPartInfoArr.count; j++) {
                    [sortArr addObject:[self.mainPartInfoArr objectAtIndex:j]];
                }
                for (int x = 0; x < k; x++) {
                    [sortArr addObject:[self.mainPartInfoArr objectAtIndex:x]];
                }
                
                self.mainPartInfoArr = sortArr;
                
                sortArr = nil;
            }
            
            self.imgArr = [NSMutableArray array];
            
            for (int i = 0; i<self.mainPartInfoArr.count; i++) {
                [self.imgArr addObject:((MainPartData *)[self.mainPartInfoArr objectAtIndex:i]).mainPartImg];
            }
            
            [picker setImageAry:self.imgArr];
            
            self.currentDefect.part = ((MainPartData *)[self.mainPartInfoArr objectAtIndex:0]).mainPartKey;
            
            self.currentDefect.partDesc = ((MainPartData *)[self.mainPartInfoArr objectAtIndex:0]).mainPartDesc;
            
//            NSMutableArray *keyArr = [NSMutableArray array];
//            NSMutableArray *valueArr = [NSMutableArray array];
//            
//            keyArr = [NSMutableArray arrayWithObjects:@"mainCode", nil];
//            valueArr = [NSMutableArray arrayWithObjects:((MainPartData *)[self.mainPartInfoArr objectAtIndex:0]).mainPartCode, nil];
//            
//            [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"detailPart.do" finishSelector:@selector(getDetailPartFinished:) failSelector:@selector(getDetailPartFailed:) delegateObj:self];
        }
        else if ([flag isEqualToString:@"1002"])
        {
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

-(void)getMainPartInfoFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)navRightButtonActionAtTag:(NSUInteger)tag
{
    //todo:返回数据
    [super backAction:nil];
}

//添加照片
-(IBAction)addPictureAction:(id)sender
{
    PIDrawerViewController *drawerController = [[PIDrawerViewController alloc] initWithNibName:@"PIDrawerViewController" bundle:nil];
    if (self.currentDefect.uploadedFile) {
        drawerController.imageEdit=self.currentDefect.uploadedFile;
    }

    [self presentViewControllerInFullRect:drawerController];
    
    drawerController.addImages=^(NSMutableArray *images){
//        if (!self.currentDefect.uploadedFile) {
//            self.currentDefect.uploadedFile=[NSMutableArray array];
//        }
        self.currentDefect.uploadedFile = [images objectAtIndex:0];
        
        [choosePictureButton setTitle:@"" forState:UIControlStateNormal];
        
        [choosePictureButton setBackgroundImage:self.currentDefect.uploadedFile forState:UIControlStateNormal];
    };
}

//保存缺陷
-(IBAction)saveAction:(id)sender
{
    self.currentDefect.senseFlag  = perception.on?@"1":@"0";
    self.currentDefect.repairFlag = repair.on?@"1":@"0";
    
    [gAlert showLoading:nil delegate:nil];

    NSMutableArray *keyArr=[NSMutableArray arrayWithObjects:@"partListValue",@"partListValue2",@"audit",@"location",@"weight",@"zone",@"respArea",@"repairFlag",@"senseFlag",@"vehicleId", nil];
    
    NSData *imgData;
    
//    NSLog(@"%lu",(unsigned long)imgData.length);
    
    if (UIImageJPEGRepresentation(self.currentDefect.uploadedFile, 1) == nil) {
        
        imgData = UIImagePNGRepresentation(self.currentDefect.uploadedFile);
        
    } else {
        
        imgData = UIImageJPEGRepresentation(self.currentDefect.uploadedFile, 0.5);
    }
    
    NSMutableArray *valueArr=[NSMutableArray arrayWithObjects:
                       [self getStr:self.currentDefect.part],
                       [self getStr:self.currentDefect.part2],
                       [self getStr:self.currentDefect.defect],
                       [self getStr:self.currentDefect.location],
                       [self getStr:self.currentDefect.weight],
                       [self getStr:self.currentDefect.zone],
                       [self getStr:self.currentDefect.resparea],
                       [self getStr:self.currentDefect.repairFlag],
                       [self getStr:self.currentDefect.senseFlag],
                       [self getStr:self.selectedCar.vehicleId],nil];
    
    if (imgData) {
        [valueArr addObject:imgData];
        [keyArr addObject:@"uploadedFile"];
    }
    
    if ([self.doSth isEqualToString:@"edit"]) {
        [keyArr addObject:@"auditId"];
        [valueArr addObject:self.currentDefect.auditId];
    }
    
    [gAlert showLoading:nil delegate:nil];
    
    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcDefectSave.do" finishSelector:@selector(addNewDefectFinished:) failSelector:@selector(addNewDefectFailed:) delegateObj:self];
}

-(NSString *)getStr:(NSString *)str
{
    return str?str:@"";
}

//请求服务器成功
-(void)addNewDefectFinished:(ASIFormDataRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json To dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回dic
        
        if ([flag isEqualToString:@"1001"]) {
            if ([self.doSth isEqualToString:@"edit"])
            {
                if (self.editDefect) {
                    self.editDefect(self.currentDefect);
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }
            else
            {
                self.currentDefect.auditId=[strDicData objectForKey:@"auditId"];
                
                if (self.addDefect) {
                    self.addDefect(self.currentDefect);
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }
        }
        else if([flag isEqualToString:@"1002"]) {

            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

//请求服务器失败
-(void)addNewDefectFailed:(ASIFormDataRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];//检查网络
}

#pragma mark - listDataPickAction
//清除对应数据
-(IBAction)cleanAction:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    
    UIButton *btnValue = [[UIButton alloc] init];
    
    switch (btn.tag) {
        case 1013:
            self.currentDefect.defect = @"";
            self.currentDefect.defectDesc = @"";
            
            btnValue = (UIButton *)[self.view viewWithTag:1003];
            break;
        case 1014:
            self.currentDefect.location = @"";
            self.currentDefect.locationDesc = @"";
            
            btnValue = (UIButton *)[self.view viewWithTag:1004];
            break;
        case 1015:
            self.currentDefect.weight = @"";
            self.currentDefect.weightDesc = @"";
            
            btnValue = (UIButton *)[self.view viewWithTag:1005];
            break;
        case 1016:
            self.currentDefect.zone = @"";
            self.currentDefect.zoneDesc = @"";
            
            btnValue = (UIButton *)[self.view viewWithTag:1006];
            break;
        case 1017:
            self.currentDefect.resparea = @"";
            self.currentDefect.respareaDesc = @"";
            
            btnValue = (UIButton *)[self.view viewWithTag:1007];
            break;
        default:
            break;
    }
    
    [btnValue setTitle:@"" forState:UIControlStateNormal];
}

-(IBAction)chooseConditionAction:(id)sender
{
    [self.searchBar resignFirstResponder];
    
    UIButton *btn = (UIButton*)sender;
    
//    [btn setTitle:@"" forState:UIControlStateNormal];
    
    DefectConditionViewController *vc = [[DefectConditionViewController alloc] init];
//    vc.fromVC=@"adddefect";
//    vc.naviTitle = btn.titleLabel.text;
    
    vc.naviTitle = [btn titleForState:(UIControlStateNormal)];
    vc.paramsDic = [NSMutableDictionary dictionary];
    switch (((UIButton *)sender).tag) {
//        case 1001:
//            [vc.paramsDic setValue:@"partList.do" forKey:@"port"];
//            break;
//        case 1002:
//            [vc.paramsDic setValue:@"partList.do" forKey:@"port"];
//            break;
        case 1003:
            [vc.paramsDic setValue:@"defectList.do" forKey:@"port"];
            
            vc.hiddenSearchBar = NO;
            
//            self.currentDefect.defect = @"";
//            self.currentDefect.defectDesc = @"";
            break;
        case 1004:
            [vc.paramsDic setValue:@"locationList.do" forKey:@"port"];
            [vc.paramsDic setValue:self.currentDefect.part2 forKey:@"value"];
            
            vc.hiddenSearchBar = YES;
            
//            self.currentDefect.location = @"";
//            self.currentDefect.locationDesc = @"";
            break;
        case 1005:
            [vc.paramsDic setValue:@"weightList.do" forKey:@"port"];
            [vc.paramsDic setValue:self.currentDefect.defect forKey:@"value"];
            
            vc.hiddenSearchBar = YES;
            
//            self.currentDefect.weight = @"";
//            self.currentDefect.weightDesc = @"";
            break;
        case 1006:
            [vc.paramsDic setValue:@"zoneList.do" forKey:@"port"];
            
            vc.hiddenSearchBar = YES;
            
//            self.currentDefect.zone = @"";
//            self.currentDefect.zoneDesc = @"";
            break;
        case 1007:
            [vc.paramsDic setValue:@"respareaList.do" forKey:@"port"];
            
            vc.hiddenSearchBar = YES;
            
//            self.currentDefect.resparea = @"";
//            self.currentDefect.respareaDesc = @"";
            break;
        default:
            break;
    }
    
    [self presentViewControllerInSmallRect:vc];
    
    vc.setText=^(NSString *key,NSString *value)
    {
        //设置选中值
        switch (((UIButton *)sender).tag) {
//            case 1001:
//                self.currentDefect.part=key;
//                self.currentDefect.partDesc=value;
//                break;
//            case 1002:
//                self.currentDefect.part2=key;
//                self.currentDefect.part2Desc=value;
//                break;
            case 1003:
                self.currentDefect.defect=key;
                self.currentDefect.defectDesc=value;
                
                btn.titleLabel.text = self.currentDefect.defectDesc;
                
                [gAlert showLoading:nil delegate:nil];
                [CommunicateWithService communicateWithService:@[@"defectList"] value:@[self.currentDefect.defect] apiName:@"weightList.do"  finishSelector:@selector(getWeightListFinished:) failSelector:@selector(getWeightListFailed:) delegateObj:self];
                break;
            case 1004:
                self.currentDefect.location=key;
                self.currentDefect.locationDesc=value;
                
//                btn.titleLabel.text = self.currentDefect.locationDesc;
                break;
            case 1005:
                self.currentDefect.weight=key;
                self.currentDefect.weightDesc=value;
                
//                btn.titleLabel.text = self.currentDefect.weightDesc;
                break;
            case 1006:
                self.currentDefect.zone=key;
                self.currentDefect.zoneDesc=value;
                
//                btn.titleLabel.text = self.currentDefect.zoneDesc;
                break;
            case 1007:
                self.currentDefect.resparea=key;
                self.currentDefect.respareaDesc=value;
                
//                btn.titleLabel.text = self.currentDefect.respareaDesc;
                break;
            default:
                break;
        }
        
        UIButton *btnSender = (UIButton *)sender;
        
        [btnSender setTitle:value forState:UIControlStateNormal];
    };
}

-(void)getWeightListFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSArray *strDicData=(NSArray *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        if ([flag isEqualToString:@"1001"]) {
//            for (int i=0; i<strDicData.count; i++) {
            if (strDicData.count>0) {
                NSDictionary *dic=(NSDictionary *)[strDicData objectAtIndex:0];
                
                self.currentDefect.weight=[dic objectForKey:@"key"];
                self.currentDefect.weightDesc=[dic objectForKey:@"value"];
                
                UIButton *btn = (UIButton*)[self.view viewWithTag:1005];
                
                [btn setTitle:self.currentDefect.weightDesc forState:(UIControlStateNormal)];
                
//                btn.titleLabel.text = self.currentDefect.defectDesc;
            }
            else
            {
                self.currentDefect.weight = @"";
                self.currentDefect.weightDesc = @"";
                
                UIButton *btn = (UIButton*)[self.view viewWithTag:1005];
                
                [btn setTitle:@"" forState:(UIControlStateNormal)];

            }
//            }
        }
        else if ([flag isEqualToString:@"1002"])
        {
            
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

-(void)getWeightListFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];//检查网络
}

-(void)getLocationListFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSArray *strDicData=(NSArray *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        if ([flag isEqualToString:@"1001"]) {
            //            for (int i=0; i<strDicData.count; i++) {
            if (strDicData.count>0) {
                NSDictionary *dic=(NSDictionary *)[strDicData objectAtIndex:0];
                
                self.currentDefect.location=[dic objectForKey:@"key"];
                self.currentDefect.locationDesc=[dic objectForKey:@"value"];
                
                UIButton *btn = (UIButton*)[self.view viewWithTag:1004];
                
                [btn setTitle:self.currentDefect.locationDesc forState:(UIControlStateNormal)];
                
//                btn.titleLabel.text = self.currentDefect.locationDesc;
            }
            else
            {
                self.currentDefect.location = @"";
                self.currentDefect.locationDesc = @"";
                
                UIButton *btn = (UIButton*)[self.view viewWithTag:1004];
                
                [btn setTitle:@"" forState:(UIControlStateNormal)];
            }
            //            }
        }
        else if ([flag isEqualToString:@"1002"])
        {
            
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

-(void)getLocationListFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];//检查网络
}


#pragma mark - UIInfiniteScrollPicker
- (void)infiniteScrollPicker:(InfiniteScrollPicker *)infiniteScrollPicker didSelectAtImage:(UIImage *)image
{
    self.searchFlag = NO;

    if (!self.isFirst) {
        self.searchBar.text = @"";
        
        self.currentDefect.part2 = nil;
        
        self.currentDefect.part2Desc = @"";
        
        self.currentDefect.location = @"";
        
        self.currentDefect.locationDesc = @"";
    }
    
    UIButton *btn = (UIButton *)[self.view viewWithTag:1004];
    
    [btn setTitle:@"" forState:UIControlStateNormal];
    
    int index = 0;

    for (int i = 0; i < self.imgArr.count; i++) {
        if ([image isEqual:[self.imgArr objectAtIndex:i]]) {
            index = i;
        }
    }
    
    self.currentDefect.part = ((MainPartData *)[self.mainPartInfoArr objectAtIndex:index]).mainPartKey;
    
    self.currentDefect.partDesc = ((MainPartData *)[self.mainPartInfoArr objectAtIndex:index]).mainPartDesc;
    
//    NSMutableArray *keyArr = [NSMutableArray array];
//    NSMutableArray *valueArr = [NSMutableArray array];
    
    NSMutableArray *keyArr = [NSMutableArray arrayWithObjects:@"mainCode", nil];
    NSMutableArray *valueArr = [NSMutableArray arrayWithObjects:((MainPartData *)[self.mainPartInfoArr objectAtIndex:index]).mainPartCode, nil];
    
    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"detailPart.do" finishSelector:@selector(getDetailPartFinished:) failSelector:@selector(getDetailPartFailed:) delegateObj:self];
    
//    NSLog(@"selected %d",index);
}

-(void)getDetailPartFinished:(ASIFormDataRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json To dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSArray *strDicData=(NSArray *)[strDic objectForKey:@"resultData"];//服务器返回dic
        
        self.detailPartInfoArr = [NSMutableArray array];
        
//        int j = 0;
        
        if ([flag isEqualToString:@"1001"]) {
            for (int i = 0; i < strDicData.count; i++) {
                NSDictionary *dic = (NSDictionary *)[strDicData objectAtIndex:i];
                
                DetailPartData *data = [[DetailPartData alloc] initWithInfo:dic];
                
//                if ([data.detailPartKey isEqualToString: self.currentDefect.part2]) {
//                    j = i;
//                }
                
                [self.detailPartInfoArr addObject:data];
            }
            
//            for (DetailPartData *obj in self.detailPartInfoArr) {
//                if ([obj.detailPartKey isEqualToString:self.currentDefect.part2]) {
//                     self.detailPartInfoArr = [NSMutableArray arrayWithObjects:[self.detailPartInfoArr objectAtIndex:j], nil];
//                }
//            }
            
            if ([self.doSth isEqualToString:@"edit"]&&self.isFirst) {
                self.isFirst = NO;
                self.searchFlag = YES;
                self.detailPartInfoSearchArr = [NSMutableArray array];
                
                self.searchBar.text = self.currentDefect.part2Desc;
            }
            
            [self.detailTableView reloadData];
            
            if (self.searchFlag) {
                if (self.detailPartInfoSearchArr.count > 0) {
                    self.currentDefect.part2 = ((DetailPartData *)[self.detailPartInfoSearchArr objectAtIndex:0]).detailPartKey;
                    self.currentDefect.part2Desc = ((DetailPartData *)[self.detailPartInfoSearchArr objectAtIndex:0]).detailPartValue;
                }
            }
            else
            {
                if (self.detailPartInfoArr.count > 0) {
                    self.currentDefect.part2 = ((DetailPartData *)[self.detailPartInfoArr objectAtIndex:0]).detailPartKey;
                    self.currentDefect.part2Desc = ((DetailPartData *)[self.detailPartInfoArr objectAtIndex:0]).detailPartValue;
                }
            }
            
            [gAlert showLoading:nil delegate:nil];
            [CommunicateWithService communicateWithService:@[@"partList"] value:@[self.currentDefect.part2] apiName:@"locationList.do"  finishSelector:@selector(getLocationListFinished:) failSelector:@selector(getLocationListFailed:) delegateObj:self];
        }
        else if([flag isEqualToString:@"1002"]) {

            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

-(void)getDetailPartFailed:(ASIFormDataRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];//检查网络
}

#pragma mark - UItableview 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchFlag) {
        return self.detailPartInfoSearchArr.count;
    }
    else
    {
        return self.detailPartInfoArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.textLabel.font = [UIFont systemFontOfSize:23.0];
    cell.textLabel.textColor = [UIColor darkGrayColor];
    if (self.searchFlag) {
        if (self.detailPartInfoSearchArr.count>0) {
            cell.textLabel.text = ((DetailPartData *)[self.detailPartInfoSearchArr objectAtIndex:[indexPath row]]).detailPartValue;
        }
    }
    else
    {
        if (self.detailPartInfoArr.count>0) {
            cell.textLabel.text = ((DetailPartData *)[self.detailPartInfoArr objectAtIndex:[indexPath row]]).detailPartValue;
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchFlag) {
        self.currentDefect.part2 = ((DetailPartData *)[self.detailPartInfoSearchArr objectAtIndex:[indexPath row]]).detailPartKey;
        self.currentDefect.part2Desc = ((DetailPartData *)[self.detailPartInfoSearchArr objectAtIndex:[indexPath row]]).detailPartValue;
        
        self.searchBar.text = self.currentDefect.part2Desc;
    }
    else
    {
        self.currentDefect.part2 = ((DetailPartData *)[self.detailPartInfoArr objectAtIndex:[indexPath row]]).detailPartKey;
        self.currentDefect.part2Desc = ((DetailPartData *)[self.detailPartInfoArr objectAtIndex:[indexPath row]]).detailPartValue;
        
        self.searchBar.text = self.currentDefect.part2Desc;
    }
    
    self.searchFlag = YES;
    
    self.detailPartInfoSearchArr = nil;
    
    [self.detailTableView reloadData];
    
    [gAlert showLoading:nil delegate:nil];
    [CommunicateWithService communicateWithService:@[@"partList"] value:@[self.currentDefect.part2] apiName:@"locationList.do"  finishSelector:@selector(getLocationListFinished:) failSelector:@selector(getLocationListFailed:) delegateObj:self];
}

#pragma mark - UISearchBar
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar becomeFirstResponder];
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText isEqualToString:@""]) {
        self.searchFlag = NO;
    }
    else
    {
        self.searchFlag = YES;
    }
    
    NSMutableArray *arr=[NSMutableArray array];
    
    for (DetailPartData *data in self.detailPartInfoArr) {
        [arr addObject:data.detailPartValue];
    }
    
    self.detailPartInfoSearchArr = [NSMutableArray array];
    
    for (int i = 0;i < self.detailPartInfoArr.count;i++) {
        if ([((DetailPartData *)[self.detailPartInfoArr objectAtIndex:i
               ]).detailPartValue containsString:searchText]) {
            [self.detailPartInfoSearchArr addObject:[self.detailPartInfoArr objectAtIndex:i]];
        }
    }
    
    [self.detailTableView reloadData];
}

@end
